var app = getApp()
var utils = require('util.js');
var dataModel = {
    model: {}
};
/**
 * 购物车减
 * @param e
 */
function bindMinus(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.num;
    // 如果只有1件了，就不允许再减了
    if (num > 1) {
        num--;
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses;
    // 将数值与状态写回
    this.setData({
        num: num,
        minusStatuses: minusStatus
    });
}
/**
 * 购物车加
 * @param e
 */
function bindPlus(e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.num;
    // 自增
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses;
    // 将数值与状态写回
    this.setData({
        num: num,
        minusStatuses: minusStatus
    });
}
//点击购物车触发的事件产品弹窗事件，展示影藏
function showModal(e) {
    var sku_info = JSON.parse(e.currentTarget.dataset.info);
    var product_name = e.currentTarget.dataset.productname;
    var productinfo = e.currentTarget.dataset.productinfo;
    var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "linear",
        delay: 0
    });
    var cart_spec = loadSkuDetail(productinfo.attribute_list); // 购物车属性数据
    this.animation = animation;
    animation.translateY(300).step();
    var standard_num = 1;
    var unit_name = '';
    var product_standard_id = '';
    var standard_list = productinfo.standard_list;
    for (var standard_key in standard_list) {
        var standard_item = standard_list[standard_key];
        if (standard_item.is_check == 1) {
            standard_num = standard_item.num;
            unit_name = standard_item.unit_name;
            product_standard_id = standard_item.id
        }
    }
    this.setData({
        product_name: product_name,
        sku_info: sku_info,
        product_info: productinfo,
        price: '--', //单个商品价格
        animationData: animation.export(),
        showModalStatus: true,
        cart_spec: cart_spec,
        standard_num: standard_num,
        unit_name: unit_name,
        product_standard_id: product_standard_id
    });
    setTimeout(function () {
        animation.translateY(0).step();
        this.setData({
            animationData: animation.export()
        })
    }.bind(this), 200);
}
/**
 * 购物车弹层点击确定
 * @param e
 * @returns {boolean}
 */
function submitcart(e) {
    var obj = this;
    var sku_info = e.currentTarget.dataset.skuinfo;
    var image = e.target.dataset.image;
    var carts_num = obj.data.num;
    sku_info['img_Url'] = image;
    var product_name = e.currentTarget.dataset.productname;
    var product_standard_id = e.currentTarget.dataset.productStandardId;
    if (sku_info == undefined) {
        wx.showToast({
            title: '请选择商品属性',
            icon: 'loading'
        });
        return false;
    }
    if (product_standard_id == undefined) {
        wx.showToast({
            title: '请选择商品规格',
            icon: 'loading'
        })
        return false;
    }
    var tmp = {sku_itmes: sku_info, name: product_name, cart_num: carts_num, product_standard_id: product_standard_id};
    //加入购物车
    utils.addCart(tmp);
    //获取缓存的购物车对象信息
    var cart_info = wx.getStorageSync('cart_info');
    obj.setData({cart_num: cart_info.length});
    // 隐藏遮罩层
    var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "linear",
        delay: 0
    })
    obj.animation = animation
    animation.translateY(300).step()
    obj.setData({
        animationData: animation.export(),
    });
    setTimeout(function () {
        animation.translateY(0).step()
        obj.setData({
            animationData: animation.export(),
            showModalStatus: false
        })
    }.bind(obj), 200)
}
/**
 * 商品规格点击事件
 * @returns {boolean}
 */
function standardItem(event) {
    var disable = event.currentTarget.dataset.disable;
    if (disable == true) {
        return true;
    }
    var product_info = {};
    var standard_list = event.currentTarget.dataset.standardList;
    var standard_list_temp = [];
    var standard_num = 1;
    var unit_name = '';
    for (var standard_key in standard_list) {
        if (standard_list[standard_key].id == event.currentTarget.dataset.id) {
            standard_list[standard_key].is_check = 1;
            standard_num = standard_list[standard_key].num
            unit_name = standard_list[standard_key].unit_name
            var basic_price = this.data.basic_price;
            if (!isNaN(basic_price) && basic_price != '') {
                this.data.price = basic_price * 100 * standard_num * 100 / 10000 + '/' + unit_name;
            }
            this.data.product_standard_id = standard_list[standard_key].id;
        } else {
            standard_list[standard_key].is_check = 0;
        }
    }
    ;
    product_info = {'standard_list': standard_list};
    this.setData({
        product_info: product_info,
        standard_num: standard_num,
        unit_name: unit_name,
        price: this.data.price,
        product_standard_id: this.data.product_standard_id
    });
}
// 购物车属性点击事件
function spec(event) {
    var group = event.currentTarget.dataset.group;
    var item = event.currentTarget.dataset.item;
    var spec_array = dataModel.model.specs;
    for (var index = 0; index < spec_array.length; index++) {
        if (spec_array[index].name == group.name) {
            for (var index2 = 0; index2 < spec_array[index].values.length; index2++) {
                var spec = spec_array[index].values[index2];
                if (spec.name == item.name) {
                    spec.checked = !spec.checked;
                }
                else {
                    spec.checked = false;
                }
            }
        }
    }
    // 添加其他属性
    refreshViewStatus();
    // 获取选中属性
    var otherChecked = getCheckedSpecs(); // 获取所有选中属性
    // 根据其他规格类型的选中情况筛选出符合条件的 sku
    var matchOtherSku = filterSku(otherChecked);
    var specLength = dataModel.model.specs.length; // 所有属性数量
    var useCheckLength = otherChecked.length; // 用户选择数量
    var price = this.data.price;
    var sku_info_checkout = '';
    if (specLength == useCheckLength && matchOtherSku.length == 1) { // 如果选中的为一个设置
        var standard_num = this.data.standard_num; // 获取规格进率
        var unit_name = this.data.unit_name;
        price = matchOtherSku[0].basic_price * 100 * standard_num * 100 / 10000 + '/' + unit_name; //设置商品单价
        var basic_price = matchOtherSku[0].basic_price;
        sku_info_checkout = matchOtherSku[0];
    } else {
        price = '--';
    }

    this.setData({
        cart_spec: dataModel,
        price: price,
        basic_price: basic_price,
        sku_info_checkout: sku_info_checkout
    });
}
// ----------------------------------------------
var allSpecs = []; // 商品全部属性列表
var skuSpecs = []; // 商品全部属性列表

function loadSkuDetail(sku) {
    allSpecs = sku.attributes; // 商品全部属性列表
    skuSpecs = sku.sku_path;  //  商品全部属性列表
    dataModel.model = {
        specs: renderViewSpecs() // 组装商品全部属性列表
    };
    refreshViewStatus();
    return dataModel;
}
function renderViewSpecs() {
    var temp = [];
    for (var i = 0; i < allSpecs.length; i++) {
        var spec = allSpecs[i];
        var m = {
            name: spec.attr_name,
            values: []
        };
        for (var j = 0; j < spec.attributes_item.length; j++) {
            m.values.push({
                name: spec.attributes_item[j],
                checked: false,
                disabled: false
            });
        }
        temp.push(m);
    }
    return temp;
}
function refreshViewStatus() {
    var specLength = dataModel.model.specs.length;
    var checked_num = specLength * (specLength - 1);
    var checked_num_temp = 0;
    // 遍历规格类型
    for (var i = 0; i < specLength; i++) {
        // 规格类型
        var specGroup = dataModel.model.specs[i];
        // 除了该规格类型的其他选中的规格
        var otherChecked = getCheckedSpecs(specGroup.name);
        // 根据其他规格类型的选中情况筛选出符合条件的 sku
        var matchOtherSku = filterSku(otherChecked);
        // 遍历该规格类型下面的所有值，确定是否可以选中
        for (var j = 0; j < specGroup.values.length; j++) {
            var spec = specGroup.values[j];

            spec.disabled = !isAnySkuMatchSpec(matchOtherSku, {
                name: specGroup.name,
                value: spec.name
            });
        }
    }
}
/**
 *  除了该规格类型的其他选中的规格
 * @param name 规格名称 例：尺寸、试用、型号
 * @param exclude_same 是否排除自己
 * @returns {Array}
 */
function getCheckedSpecs(name) {
    var temp = [];
    for (var i = 0; i < dataModel.model.specs.length; i++) {
        var specGroup = dataModel.model.specs[i];

        // 排除同一个
        if (name == specGroup.name)
            continue;

        // 选中的
        for (var j = 0; j < specGroup.values.length; j++) {
            var spec = specGroup.values[j];
            if (spec.checked) {
                temp.push({
                    name: specGroup.name,
                    value: spec.name
                });

                break;
            }
        }
    }

    return temp;
}
// 根据其他规格类型的选中情况筛选出符合条件的 sku
function filterSku(checkedSpecs) {
    var temp = [];

    // 遍历 Sku
    for (var i = 0; i < skuSpecs.length; i++) {
        var sku = skuSpecs[i];

        // 遍历选中的规格，找到匹配所有选中规格的 Sku
        var isMatched = true;
        for (var j = 0; j < checkedSpecs.length; j++) {
            var spec = checkedSpecs[j];

            if (!isSkuMatchSpec(sku, spec)) {
                isMatched = false;
                break;
            }
        }

        if (isMatched)
            temp.push(sku);
    }

    return temp;
}
function isSkuMatchSpec(sku, spec) {
    for (var i = 0; i < sku.sku_attr_info.length; i++) {
        var skuSpec = sku.sku_attr_info[i];
        if (skuSpec.attr_name == spec.name && skuSpec.attr_value == spec.value)
            return true;
    }

    return false;
}
function isAnySkuMatchSpec(skus, spec) {
    for (var i = 0; i < skus.length; i++) {
        if (isSkuMatchSpec(skus[i], spec))
            return true;
    }

    return false;
}
module.exports = {
    submitcart: submitcart,
    standardItem: standardItem,
    spec: spec, // 购物车属性点击事件
    showModal: showModal, // 点击购物车触发的事件产品弹窗事件
    bindMinus:bindMinus, // 购物车减
    bindPlus:bindPlus // 购物车加
};